﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using HelpCentral.Data.Model;
using HelpCentral.Data.Repository;
using HelpCentral.Shared.Interfaces;
using HelpCentral.Configuration;
using HelpCentral.Core.Objects;
using HelpCentral.Shared.Enums;

namespace HelpCentral.Core.Services
{
    public class ClientService
    {
        public ClientService()
        {
            CoreContainer.Register<IClient, ClientInfo>();
            CoreContainer.Register<IClientRepository, ClientRepository>();
        }

        public IClient SaveClient(IClient client)
        {
            client.Validate();
            
            var cr = CoreContainer.ResolveNew<IClientRepository>();
            bool isNew = cr.FetchClientById(client.ClientId) == null;

            client = cr.CommitClient(client);

            if (isNew)
            {
                new AuditService().SaveAuditEvent(AuditEventType.CreateClientEvent, client, "Added new client with license '" + client.License.ToString() + "'", client.ClientId);
            }
            else
            {
                new AuditService().SaveAuditEvent(AuditEventType.UpdateClientEvent, client, "Updated client", client.ClientId);
            }

            return client;
        }

        public IClient GetClientByLicense(Guid license)
        {
            var cr = CoreContainer.ResolveNew<IClientRepository>();

            return cr.FetchClientByLicense(license);
        }

        public IEnumerable<IClient> GetClients(bool onlyActive)
        {
            var cr = CoreContainer.ResolveNew<IClientRepository>();

            if (onlyActive)
            {
                return cr.FetchActiveClients();
            }
            else
            {
                return cr.FetchAllClients();
            }
        }
    }
}
